import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/provider/UserInforModel.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/custom/price_input_dialog.dart';
import 'package:flutter_juwo/ui/model/account_money_entity.dart';
import 'package:flutter_juwo/ui/model/money_flow_entity.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:provider/provider.dart';

import 'model/response_entity.dart';

///************************
/// @auther nb
/// @function 我的金币
/// @创建日期 2019/10/08 15:31
///************************
class MyGold extends StatefulWidget {
  @override
  _MyGoldState createState() => _MyGoldState();
}

class _MyGoldState extends State<MyGold> {
  MyPageState ps = MyPageState.LOADING;
  AccountMoneyEntity entity = null;
  MoneyFlowEntity moneyFlowEntity = null;
  int currentPage = 1;
  int totlePage = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: UiUtils.appBar(context, "我的金币"),
      body: this.getBody(),
    );
  }

  getBody() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.HAVE_DATA) {
      return this.getContent();
    }

    return Container();
  }

  Future getData() {
    FormData params = FormData.from({"type": "2"});
    DioManager.getInstance().get(Api.USER_ACCOUNT, params, (json) {
      entity = AccountMoneyEntity.fromJson(json);

      print("获取账户：$json");
      if (null == entity) {
        Application.router.pop(context);
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return;
      }

      if (entity.code == Api.SUCCESS_CODE) {
        Provider.of<UserInforModel>(context).updateGold(entity.data.account);
        currentPage = 1;
        ps = MyPageState.HAVE_DATA;
        setState(() {});
        return;
      }

      if (entity.code == Api.ERROR_CODE || entity.code == Api.ERROR_CODE_0) {
        ToastUtil.showShortErrToast(entity.message);
        return;
      }
    }, (err) {
      ToastUtil.showShortErrToast(err);
    });
  }


  getContent() {
    List<Widget> list = [];
    list.add(this.getTip());
    list.add(this.getTop());
    list.add(UiUtils.divider(height: 10));
    list.add(this.getBottom());
    list.add(UiUtils.divider(height: 1));
    return Container(
      child: Column(
        children: list,
      ),
    );
  }

  Widget getTip() {
    return Container(
      //  margin: EdgeInsets.all(ScreenUtil().setWidth(30)),
      height: ScreenUtil().setWidth(120),
      width: ScreenUtil().setWidth(750),
      decoration: getDecoration(),
      child: Container(
        alignment: Alignment.center,
        child: Text(
          " 金币不能直接提现，请兑换余额后提现",
          style: getTextStyle(),
        ),
      ),
    );
  }

  getTop() {
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          UiUtils.divider(),

          ///可用余额
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(30)),
            child: Text(
              "${entity.data.account}",
              style: TextStyles.custom(
                  60, Color(0xFFff631c), Font.PingFangMedium),
            ),
          ),
          Container(
            child: Text(
              "可用金币（金）",
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangMedium),
            ),
          ),

          ///待返，累计
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(60)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                Container(
                  child: Column(
                    children: <Widget>[
                      Container(
                        child: Text(
                          "${entity.data.accountFrozen}",
                          style: TextStyles.custom(
                              30, Colours.appC2, Font.PingFangMedium),
                        ),
                      ),
                      Container(
                        child: Text(
                          "待返金币（金）",
                          style: TextStyles.custom(
                              26, Colours.appC2, Font.PingFangMedium),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  child: Column(
                    children: <Widget>[
                      Container(
                        child: Text(
                          "${entity.data.sumAccount}",
                          style: TextStyles.custom(
                              30, Colours.appC2, Font.PingFangMedium),
                        ),
                      ),
                      Container(
                        child: Text(
                          "累计金币（金）",
                          style: TextStyles.custom(
                              26, Colours.appC2, Font.PingFangMedium),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),

          GestureDetector(
            onTap: () {
              ///提现
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return PriceInputDialog(
                      title: "兑换数量",
                      onPressed: (value) {
                        ///1.大于10，

                        if (double.parse(value) >
                            double.parse(entity.data.account)) {
                          ToastUtil.showShortErrToast("兑换数量不能大于可用金币数！");
                          return;
                        }

                        ///2.小于 可用金币
                        if (double.parse(value) < 10) {
                          ToastUtil.showShortErrToast("10金币及以上才可以兑换！");
                          return;
                        }
                        print("$value");
                        NavigatorUtils.goBack(context);
                        showMyDialog();

                        ///兑换
                        this.exchange(value);
                      },

                    );
                  });
            },
            child: Container(
              margin: EdgeInsets.fromLTRB(
                  ScreenUtil().setWidth(30),
                  ScreenUtil().setWidth(60),
                  ScreenUtil().setWidth(30),
                  ScreenUtil().setWidth(60)),
              width: ScreenUtil().setWidth(750),
              height: ScreenUtil().setWidth(80),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Colours.appC16,
                  borderRadius: BorderRadius.circular(20)),
              child: Text(
                "兑换余额",
                style: TextStyles.custom(
                    30, Colours.white, Font.PingFangMedium),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget getBottom() {
    return GestureDetector(
      onTap: () {
        NavigatorUtils.push(context, Routes.goldFlow);
      },
      child: Container(
        padding: EdgeInsets.all(ScreenUtil().setWidth(30)),
        alignment: Alignment.centerLeft,
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              "流水记录",
              style: TextStyles.custom(
                  32, Colours.appC16, Font.PingFangRegular),
            ),
            Image.asset(
              Utils.getImgPath("icon_right_01"),
              width: ScreenUtil().setWidth(40),
            )
          ],
        ),
      ),
    );
  }

  Widget getItem(MoneyFlowDataRe res) {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(30)),
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
                child: Text(
                  res.type == "1" ? "兑换余额" : "任务佣金",
                  style: TextStyles.custom(
                      28, Colours.appC2, Font.PingFangMedium),
                ),
              ),
              Container(
                child: Text(
                  res.type == "2" ? "+${res.money}金" : "-${res.money}金",
                  style: TextStyles.custom(
                      28,
                      res.type == "2" ? Colours.appC16 : Colours.appC2,
                      Font.PingFangMedium),
                ),
              ),
              Container(
                padding: EdgeInsets.only(right: ScreenUtil().setWidth(30)),
                child: Text(
                  "${res.createTime}",
                  style: TextStyles.custom(
                      28, Colours.appC3, Font.PingFangMedium),
                ),
              )
            ],
          ),
          Container(
            child: UiUtils.divider(),
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(30)),
          )
        ],
      ),
    );
  }

  void showMyDialog() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new LoadingDialog(
            text: "正在提交…",
          );
        });
  }

  void exchange(String value) {
    FormData formData = FormData.from({"money": value});
    DioManager.getInstance().post(Api.USER_WITHDRAW, formData, (json) async {
      ResponseEntity entity = ResponseEntity.fromJson(json);
      print("兑换：$json");
      if (null == entity) {
        NavigatorUtils.goBack(context);
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return;
      }
      if (entity.code == Api.SUCCESS_CODE.toString()) {
        var result = await this.getData();
        NavigatorUtils.goBack(context);
        return;
      }
      ToastUtil.showShortErrToast(entity.message);
    }, (err) {
      print("兑换err：$err");
      ToastUtil.showShortErrToast(err);
      NavigatorUtils.goBack(context);
    });
  }

  getDecoration() {
    return BoxDecoration(
        borderRadius: BorderRadius.circular(0), color: Colors.amberAccent[700]);
  }

  getTextStyle() {
    return TextStyles.custom(30, Colours.white, Font.PingFangRegular);
  }
}
